package com.cw.jeeyt.service.impl.security;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.cw.jeeyt.service.bo.security.SecurityUserBo;
import com.cw.jeeyt.dao.domain.security.SecurityRoleModel;
import com.cw.jeeyt.dao.domain.security.SecurityUserModel;
import com.cw.jeeyt.dao.intf.security.SecurityRoleDao;
import com.cw.jeeyt.dao.intf.security.SecurityUserDao;
import com.cw.jeeyt.service.converter.security.SecurityRoleConverter;
import com.cw.jeeyt.service.converter.security.SecurityUserConverter;

/**
 * 用户详情业务实现类
 *
 * @author: chenw
 * @create: 2018-11-08 11:40
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SecurityUserDao securityUserDao;
    @Autowired
    private SecurityRoleDao securityRoleDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        SecurityUserModel securityUser = securityUserDao.findUserByName(username);
        if (securityUser == null) {
            return null;
        }
        //查询用户角色信息
        List<SecurityRoleModel> roles = securityRoleDao.getRolesByUserId(securityUser.getId());
        if (securityUser != null) {
            SecurityUserBo securityUserBo = SecurityUserConverter.model2Bo(securityUser);
            if (roles != null) {
                StringBuilder roleNames = new StringBuilder("");
                securityUserBo.setRoles(SecurityRoleConverter.modelList2BoList(roles));
                int i = 0;
                for (SecurityRoleModel role : roles) {
                    if (i == 0) {
                        roleNames.append(role.getName());
                    } else {
                        roleNames.append("," + role.getName());
                    }
                    i++;
                }
                securityUserBo.setRoleNames(roleNames.toString());
            }
            return securityUserBo;
        }
        return null;
    }
}
